package com.example.group.network.express_plus_app;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;


import com.example.group.network.express_plus_app.bean.MyResponse;

import com.example.group.network.express_plus_app.ui.login.LoginActivity;
import com.example.group.network.express_plus_app.viewmodel.RegisterViewModel;
import com.example.group.network.express_plus_app.viewmodel.bean.RegisterFormState;
import com.example.group.network.express_plus_app.viewmodel.factory.RegisterViewModelFactory;

public class UserRegisterActivity extends AppCompatActivity implements View.OnClickListener {

    private RegisterViewModel registerViewModel;
    ProgressBar loadingProgressBar;
    EditText phoneEditText;
    EditText passwordEditText;
    EditText rePasswordEditText;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_register);
        //标题栏设置
        ActionBar supportActionBar = getSupportActionBar();
        supportActionBar.setDisplayHomeAsUpEnabled(true);
        supportActionBar.setHomeAsUpIndicator(R.drawable.ic_baseline_arrow_back_ios_24);
        supportActionBar.setTitle("注册");

        registerViewModel = new ViewModelProvider(this, new RegisterViewModelFactory())
                .get(RegisterViewModel.class);
        phoneEditText = findViewById(R.id.rg_phone);
        passwordEditText = findViewById(R.id.rg_password);
        rePasswordEditText = findViewById(R.id.rg_re_password);
        final Button registerButton = findViewById(R.id.re_register);
        registerButton.setOnClickListener(this);
        loadingProgressBar = findViewById(R.id.re_loading);
        registerViewModel.getRegisterFormState().observe(this, new Observer<RegisterFormState>() {
            @Override
            public void onChanged(@Nullable RegisterFormState registerFormState) {
                if (registerFormState == null) {
                    return;
                }
                registerButton.setEnabled(registerFormState.isDataValid());
                if (registerFormState.getPhoneError() != null) {
                    phoneEditText.setError(getString(registerFormState.getPhoneError()));
                }
                if (registerFormState.getPasswordError() != null) {
                    passwordEditText.setError(getString(registerFormState.getPasswordError()));
                }
                if (registerFormState.getRePasswordError()!=null){
                    rePasswordEditText.setError(getString(registerFormState.getRePasswordError()));
                }
            }
        });

        registerViewModel.getRegisterResult().observe(this, new Observer<MyResponse>() {
            @Override
            public void onChanged(@Nullable MyResponse registerResult) {
                if (registerResult == null) {
                    return;
                }
                loadingProgressBar.setVisibility(View.GONE);
                if (!registerResult.getOk()) {
                    showToast("该电话已注册");
                }
                if (registerResult.getOk()) {
                    Intent intent = new Intent(UserRegisterActivity.this, LoginActivity.class);
                    startActivity(intent);
                    showToast("注册成功!");
                }
                setResult(Activity.RESULT_OK);

                //Complete and destroy login activity once successful
                finish();
            }
        });

        TextWatcher afterTextChangedListener = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // ignore
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // ignore
            }

            @Override
            public void afterTextChanged(Editable s) {
                registerViewModel.registerDataChanged(phoneEditText.getText().toString(),
                        passwordEditText.getText().toString(),rePasswordEditText.getText().toString());
            }
        };

        phoneEditText.addTextChangedListener(afterTextChangedListener);
        passwordEditText.addTextChangedListener(afterTextChangedListener);
        rePasswordEditText.addTextChangedListener(afterTextChangedListener);
        //在输入完按确定键也可以自动注册
        rePasswordEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    registerViewModel.register(phoneEditText.getText().toString(),
                            passwordEditText.getText().toString(), UserRegisterActivity.this);
                }
                return false;

            }
        });
    }

    //返回按钮
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId()==android.R.id.home){
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View v) {
        loadingProgressBar.setVisibility(View.VISIBLE);
        //login(usernameEditText.getText().toString(),passwordEditText.getText().toString());
        registerViewModel.register(phoneEditText.getText().toString(),
                passwordEditText.getText().toString(), UserRegisterActivity.this);

    }

    private void showToast(String desc) {
        Toast.makeText(getApplicationContext(), desc, Toast.LENGTH_SHORT).show();
    }
}